<template>
  <div style="width: 95%;margin: auto;">
    <!-- 
        :inline :把el-form-item 设置 行内元素
         -->
    <el-form :inline="true" :model="userFrom" class="demo-form-inline">
      <el-form-item style="width: 180px;">
        <el-input v-model="userFrom.username" placeholder="请输入姓名" clearable />
      </el-form-item>
      <el-form-item style="width: 180px;">
        <el-select v-model="userFrom.type" placeholder="请选择类型" clearable>
          <el-option label="管理员" value="1" />
          <el-option label="业主用户" value="2" />
        </el-select>
      </el-form-item>
      <el-form-item style="width: 180px;">
        <el-input v-model="userFrom.remarks" placeholder="备注" clearable />
      </el-form-item>
      <el-form-item style="width: 180px;">
        <el-select v-model="userFrom.isdelete" placeholder="是否删除" clearable>
          <el-option label="未删除" value="0" />
          <el-option label="已删除" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="findAll(1)">查询</el-button>
      </el-form-item>
    </el-form>
  </div>
  <div style="width: 95%;margin: auto;">
    <el-button type="primary" :icon="Plus" @click="showDialog()"></el-button>
    <el-button type="primary" :icon="Delete" @click="batchedDeleteByIds()">批量删除</el-button>
  </div>
  <el-table :data="userPage.users" style="width: 95%; margin: auto;" @selection-change="handleSelectionChange">
    <!-- 添加复选框选项 -->
    <el-table-column type="selection" width="55" />
    <el-table-column label="编号" prop="id" width="150px" fixed />
    <el-table-column label="姓名" prop="username" width="150px" />
    <el-table-column label="角色信息" width="200px">
      <!-- 插槽 -->
      <template #default="scope">
        <span v-for="(role, index) in scope.row.roles">
          <el-tag v-if="role.rname == '管理员'" type="primary" style="width: 65px;">{{ role.rname }}</el-tag>
          <el-tag v-else-if="role.rname == '业主用户'" type="danger" style="width: 65px;">{{ role.rname }}</el-tag>
          <el-tag v-else-if="role.rname == 'java高手'" type="success" style="width: 65px;">{{ role.rname }}</el-tag>
          <el-tag v-else type="info" style="width: 65px;">{{ role.rname }}</el-tag>
        </span>
      </template>
    </el-table-column>
    <el-table-column label="类型" prop="type" width="150px">
      <!-- 插槽 -->
      <template #default="scope">
        <el-tag v-if="scope.row.type == 1" type="primary">管理员</el-tag>
        <el-tag v-else type="danger">业主</el-tag>
      </template>
    </el-table-column>
    <el-table-column label="备注" prop="remarks" width="150px" />
    <el-table-column label="头像" prop="imgPath" width="150px">
      <!-- 插槽 -->
      <template #default="scope">
        <!-- <el-image style="width: 80px;border-radius: 5%;":src="scope.row.imgPath"/> -->
        <el-avatar shape="circle" :size="50" :src="scope.row.imgPath" />
      </template>
    </el-table-column>
    <el-table-column label="是否可用" prop="isdelete" width="150px">
      <!-- 插槽 -->
      <template #default="scope">
        <el-tag v-if="scope.row.isdelete == 0" type="primary">可用</el-tag>
        <el-tag v-else type="danger">不可用</el-tag>
      </template>
    </el-table-column>
    <el-table-column width="150px" fixed="right" label="操作">
      <template #default="scope">
        <!-- <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button> -->
        <el-button type="primary" :icon="Edit" circle @click="handleEdit(scope.$index, scope.row)" />
        <el-button type="danger" :icon="Delete" circle @click="handleDelete(scope.row)" />
        <el-button type="success" :icon="Setting" circle @click="updateRoleBtn(scope.row)" />
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页插件 -->
  <div style="width: 95%;margin: 10px auto;">
    <el-pagination background layout="prev, pager, next" v-model:page-size="userFrom.pageSize"
      v-model:current-page="userFrom.pageNum" :total="userFrom.total" @current-change="findAll" />
  </div>
  <div>
    <!-- 新增用户和修改对话框 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="25%" draggable>
      <!-- 新增用户表单 -->
      <el-form :inline="true" :model="dialog.user" class="demo-form-inline">
        <el-form-item>
          <el-input v-model="dialog.user.username" placeholder="请输入用户名" clearable style="width: 200px;height: 35px;" />
        </el-form-item>
        <!-- 显示上传图片 -->
        <div
          style="position:  absolute;top: 50px;left: 240px; width: 30%; height: 100px;background-color:#FAFAFA ;text-align: center;border-radius: 5px;">
          <el-image @click="showUploadImageDialog()" :src="dialog.user.imgPath"
            style="border-radius: 5%;width: 100%;height: 100%;" />
          <!-- <el-button @click="showUploadImageDialog()" style="width: 90px;height: 10px;background-color: #FAFAFA;line-height: 10px;font-size: 12px;">添加图片</el-button> -->
        </div>

        <el-select v-model="dialog.user.type" placeholder="选择用户类型" clearable style="width: 200px;">
          <!-- label：表示显示文本内容  value:表示提交值 -->
          <el-option label="管理员" :value="1" />
          <el-option label="业主用户" :value="2" />
        </el-select>
        <el-input v-model="dialog.user.remarks" :rows="2" type="textarea" placeholder="输入备注信息"
          style="width: 340px;margin-top: 20px;" />
        <el-form-item style="margin-top: 20px;">
          <el-button type="primary" @click="insertAndUpdateUser">{{ dialog.btnText }}</el-button>
          <el-button type="primary" @click="clearFormData">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>

  <div>
    <!-- 新增用户和修改对话框 -->
    <el-dialog v-model="uploadDialog.visible" title="文件上传" width="30%" draggable>
      <el-upload :action="uploadDialog.uploadUrl" list-type="picture-card" :file-list="fileList"
        :limit="uploadDialog.limit" :auto-upload="uploadDialog.autoUpload" :on-change="handlerImage">
        <el-icon>
          <Plus />
        </el-icon>
      </el-upload>
      <!-- 添加上传按钮 -->
      <el-form-item style="margin-top: 10px;margin-left: 320px;">
        <el-button type="primary" @click="uploadHandler()">上传</el-button>
      </el-form-item>
    </el-dialog>
  </div>

  <div>
    <!-- 分配角色对话框 -->
    <el-dialog v-model="updateRole.visible" :title="updateRole.title" width="25%" draggable>
      <el-form :inline="true" :model="updateRole.user" class="demo-form-inline">
        <div>
          当前用户:
          <span>{{ updateRole.user.username }}</span>
        </div>
        <hr>
        </hr>
        <el-checkbox v-model="updateRole.checkAll" :indeterminate="updateRole.isIndeterminate"
          @change="handleCheckAllChange">
          全选
        </el-checkbox>
        <el-checkbox-group v-model="updateRole.checkedCities" @change="handleCheckedCitiesChange">
          <el-checkbox v-for="role in updateRole.cities" :key="role.rid" :label="role.rid">
            {{ role.rname }}
          </el-checkbox>
        </el-checkbox-group>
        <el-button type="primary" @click="updateRoleOk()" style="margin-left: 250px;">确认分配</el-button>
      </el-form>
    </el-dialog>
  </div>

</template>
<script setup>
//1.引入ref和reactive
import { ref, reactive, onMounted } from 'vue';
import request from '../utils/request';
import { Delete, Edit, Plus, Setting } from '@element-plus/icons-vue'

import { ElMessage } from 'element-plus'

const userPage = reactive({
  users: [], //存放后端查询用户数据变量

})

//声明一个对象，用于条件查询
let userFrom = ref({
  pageNum: 0,
  pageSize: 5,
  total: 0
})
//定义对话框属性
let dialog = ref({
  visible: false,
  title: '',
  btnText: '',
  user: {
    username: '',
    type: '',
    remarks: '',
    imgPath: '',
  }
})
//定义分配角色对话属性
let updateRole = reactive({
  visible: false,
  title: '',
  checkAll: false,
  isIndeterminate: true,
  checkedCities: [],
  cities: [],
})

//角色分配相关方法
const handleCheckAllChange = (val) => {
  updateRole.checkedCities = val ? updateRole.cities : []
  updateRole.isIndeterminate = false
}
const handleCheckedCitiesChange = (value) => {
  const checkedCount = value.length
  updateRole.checkAll = checkedCount === updateRole.cities.length
  updateRole.isIndeterminate = checkedCount > 0 && checkedCount < updateRole.cities.length
}
//打开分配角色按钮
const updateRoleBtn = async(row) => {

  //显示表单信息
  updateRole.user = row;
  //初始化选项信息
  handleCheckedCitiesChange(row.roles);
  //设置对话框标题
  updateRole.title = "分配角色";
  //显示所有身份
  if (updateRole.cities.length == 0) {
    await request.get("/roles/findAll").then(res => {
      updateRole.cities = res.data.data;
    })
  }
  //回显角色当前身份
  updateRole.checkedCities = row.roles.map(role => role.rid);
  //显示对话框
  updateRole.visible = true;

}
//确认分配按钮
const updateRoleOk = () => {
  request.put(`/user/updateUserRole/${updateRole.checkedCities}`,updateRole.user).then(res =>{

    if(res.data.success){
      findAll(userFrom.value.pageNum);
      updateRole.visible=false;
    }
  })
}

//定义变量控制文件上传
const uploadDialog = reactive({
  visible: false, //隐藏对话框
  uploadUrl: "",
  fileList: [], //保存所有上传文件集合
  limit: 1,//控制文件上传个数
  autoUpload: false,
  uploadFile: null,
})

//实现用户新增或者修改操作
const insertAndUpdateUser = async () => {
  // console.log(dialog.value.user); //查询是否有值
  if (dialog.value.btnText != "更新数据") {
    //1.发送请求实现新增用户功能
    let res = await request.post("/user/insert", dialog.value.user);
    //判断新增成功
    if (res.data.success) {
      //1.清空表单
      clearFormObj();
      // dialog.owner = {};
      //2.刷新页面
      findAll(1);
      //3.显示提示信息
      ElMessage.success("添加成功")
      //4.关闭对话框
      dialog.value.visible = false;
    }
  } else {
    let res = await request.put("/user/update", dialog.value.user);
    //判断新增成功
    if (res.data.success) {
      //1.清空表单
      clearFormObj();
      // dialog.owner = {};
      //2.刷新页面
      findAll(userFrom.value.pageNum);
      //3.显示提示信息
      ElMessage.success("修改成功")
      //4.关闭对话框
      dialog.value.visible = false;
    }
  }
}

//实现文件上传函数
const uploadHandler = async () => {
  //文件上传详细步骤
  //1.创建FormData对象
  let formData = new FormData();
  //2.设置上传对象对象
  formData.append("file", uploadDialog.uploadFile)
  //3.设置上传类型
  let contentType = { "ContentType": "multipart/form-data" }
  formData.append("headers", contentType);
  //4.发送请求实现文件上传
  let res = await request.post("/user/fileUpload", formData);
  // console.log(res.data);
  if (res.data.success) {
    //把上传文件保存到表单imgPath中
    dialog.value.user.imgPath = res.data.data; //http://localhost:80/xxxx.png
    //显示提示信息
    ElMessage.success("上传成功");
    //关闭文件上传对话框
    uploadDialog.visible = false;
  }
}

//选中文件时触发函数
const handlerImage = (file) => {
  uploadDialog.uploadFile = file.raw;
}
//显示文件上传对话框
const showUploadImageDialog = () => {
  uploadDialog.visible = true;
}

//显示修改用户对话框
const handleEdit = (index, row) => {
  //显示表单信息
  dialog.value.user = row;
  //设置对话框标题
  dialog.value.title = "修改用户";
  //设置按钮文本内容
  dialog.value.btnText = "更新数据";
  //显示对话框
  dialog.value.visible = true;
}

//显示新增对话框
const showDialog = () => {
  //1.设置对话框标题
  dialog.value.title = "新增用户";
  //2.设置对话框 案例文本
  dialog.value.btnText = "新增";
  //3.清空表单
  clearFormObj();
  //4.显示对话框
  dialog.value.visible = true;
}

//清空表单函数
const clearFormObj = () => {
  dialog.value.user.username = '';
  dialog.value.user.type = 2;
  dialog.value.user.remarks = '';
  dialog.value.user.imgPath = 'https://org-yixue-ykj-bucket.oss-cn-nanjing.aliyuncs.com/avatar/cxy.jpg';
}


//根据条件查询用户信息
const findAll = async (currentpage) => {
  userFrom.value.pageNum = currentpage;
  let res = await request.get("/user/queryCondition", { params: userFrom.value });
  // console.log(res);
  if (res.data.success) {
    userPage.users = res.data.data.list;
    userFrom.value.pageNum = res.data.data.pageNum;
    userFrom.value.pageSize = res.data.data.pageSize;
    userFrom.value.total = res.data.data.total;
  }
}

//当实例挂载到元素之后触发onMounted
onMounted(() => {
  //1.调用方法实现，查询用户数据
  findAll(1);
})
</script>